package com.pluto.stack;

import java.util.Iterator;

/**
 * 栈的链表实现
 * 链表头作为栈顶
 */
public class Stack<Item> implements Iterable<Item> {

    /**
     * 节点嵌套类
     */
    private class Node {
        Item item;
        Node next;
    }


    private Node first;     //存储栈顶节点,从栈顶进栈和出栈
    private int N;

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        N++;
    }

    /**
     * 没有对first进行检查,可能first为null,此时会抛出 java.lang.NullPointerException
     * @return
     */
    public Item pop() {
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }

    /**
     * 实现迭代器
     * @return
     */
    @Override
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<Item> {

        private Node node = first;

        @Override
        public boolean hasNext() {
            return node != null;
        }

        @Override
        public Item next() {
            Item item = node.item;
            node = node.next;
            return item;
        }
    }


    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("hello");
        stack.push("world");
        for (String s : stack) {
            System.out.println(s);
        }
    }
}
